package com.zlf.config;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.setResponseStatus;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * 自定义GlobalFilter
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (validateToken(token)) {
            return chain.filter(exchange);
        } else {
            setResponseStatus(exchange, HttpStatus.FOUND);

            final ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().set(HttpHeaders.LOCATION, "http://www.baidu.com");
            return response.setComplete();
        }
    }

    private boolean validateToken(String token) {
        return !StringUtils.isEmpty(token) && token.startsWith("demo-");
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
